package com.jlz.managers.user;

import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jlz.beans.user.AdminBean;
import com.julewa.db.DB;
import com.julewa.db.Identifier;

@Service
public class Admins {
	public static final int ADMINISTRATOR = -1024;
	public static final int MANAGER = -1;
	
	private @Autowired Identifier idsrv;
	private @Autowired DB db;
	
	@SuppressWarnings("unused")
	@PostConstruct
	private void init(){
		AdminBean admin = this.find("admin");
		if(admin != null)return;
		admin = create();
		admin.setType(ADMINISTRATOR);
		admin.setName("系统管理员");
		admin.setUsercode("admin");
		admin.setPassword("admin");
		admin.setState(State.USING.getValue());
		admin.setDescription("auto created administrator");
		//
		this.save(admin);
	}
	
	public enum State{
		NEW(0),
		USING(1),
		LOCKED(3)
		;
		private int value = 0;
		private State(int v){value = v;}
		public int getValue(){return value;};
		public String getName(){return name();};
		public static State of(int v){
			for(State s:State.values()){
				if(s.value == v)return s;
			}
			return null;
		}
	}
	
	public AdminBean create(String name){
		AdminBean admin = create();
		admin.setType(MANAGER);
		return admin;
	}

	public AdminBean create(){
		return db.create(AdminBean.class);
	}
	
	public AdminBean get(long adminId){
		return (AdminBean)db.getObject("admin.object", adminId);
	}
	
	public AdminBean find(String code){
		return (AdminBean)db.getObject("admin.byCode", code);
	}
	
	public boolean save(AdminBean admin){
		if(admin.getID() == null){
			admin.setID(idsrv.generate("admin"));
			return db.insert("admin.insert", admin);
		}else{
			return db.update("admin.update", admin);
		}
	}
	
	public boolean remove(AdminBean admin){
		if(admin.getID() == null)return false;
		return db.delete("admin.delete", admin);
	}
	
	@SuppressWarnings("unchecked")
	public List<AdminBean> all(){
		return db.getList("admin.all", null);
	}
}
